package com.gln.bloger.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.hibernate.Hibernate;

import com.gln.bloger.dao.WebsiteDao;
import com.gln.bloger.exception.BlogerException;
import com.gln.bloger.log.Logging;
import com.gln.bloger.pojos.User;
import com.gln.bloger.pojos.Website;
import com.gln.bloger.service.WebsiteService;

public class WebsiteServiceImpl implements WebsiteService {
    private WebsiteDao websiteDao;
    
	public WebsiteDao getWebsiteDao() {
		return websiteDao;
	}

	public void setWebsiteDao(WebsiteDao websiteDao) {
		this.websiteDao = websiteDao;
	}

	public Website getWebsite(String handle) throws BlogerException {
		Website website = this.getWebsiteDao().getByHandle(handle);
		Logging.info("force initialize proxy's associate object");
		Hibernate.initialize(website.getCreator());
		return website;
	}

	public Website getWebsiteById(String id) throws BlogerException {
		return this.getWebsiteDao().get(id);
	}

	/**
	 * 
	 * @param creator
	 * @return
	 * @throws BlogerException
	 */
	public List<Website> getWebsites(User creator)
			throws BlogerException {
		List<Website> websites = getWebsiteDao().getByCreator(creator);
		return websites;
	}
	/**
	 *read available themes
	 * @return
	 * @throws BlogerException
	 */
	@SuppressWarnings("unchecked")
	public List<String> getThemes() throws BlogerException {
		 SAXReader reader = new SAXReader();
		 try{
	        Document document = reader.read(this.getClass().getResource("/")
	        		+"resources/themes.xml");
	        Element root = document.getRootElement();

	        List<String> themes = new ArrayList<String>();
	        // iterate through child elements of root
	        for ( Iterator i = root.elementIterator(); i.hasNext(); ) {
	            Element element = (Element) i.next();
	            if("theme".equals(element.getName())){
	            	themes.add((String)element.getData());
	            }
	        }
	        return themes;
		 }catch (Exception e) {
			e.printStackTrace();
		}
		 return null;
	}

	public void saveOrUpdateWebsite(Website website) throws BlogerException {
		this.getWebsiteDao().saveOrUpdate(website);
	}	
}
